package com.webchat.netty.server.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import static com.webchat.common.constants.NettySocketConstants.CHAT_WEBSOCKET_PATH;

public class NettyWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {

        ChannelPipeline pipeline = socketChannel.pipeline();

        // 设置http请求编解码处理器，使用默认的
        pipeline.addLast(new HttpServerCodec());

        // 合并http请求，设置允许请求数据大小，默认64kb
        pipeline.addLast(new HttpObjectAggregator(65536 * 5));

        // 请求处理handler
        pipeline.addLast(new NettyWebSocketRequestHandler());

        // websocket 协议处理
        pipeline.addLast(new WebSocketServerProtocolHandler(CHAT_WEBSOCKET_PATH));

        // 自定义消息(websocket 数据帧)处理handler
        pipeline.addLast(new NettyWebSocketMessageHandler());
    }
}
